package com.zrrd.jt_admin.common.intercept;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author WanJl
 * @version 1.0
 * @title TokenIntercriptor
 * @description
 * @create 2024/7/2
 */
@Slf4j
public class TKInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 前端发送过来的请求头中的属性名
     */
    private static final String HEADER_NAME = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取所有请求的请求头的token属性值
        String token = request.getHeader(HEADER_NAME);

        //不能让登录功能，都显示未登录，所以需要放行登录的接口
        String url = request.getRequestURI().substring(request.getContextPath().length());

        log.info("当前的发送请求是发给--->"+url+"的");

        //判断如果是**/login 就放行
        if (url.contains("/login")){
            log.info("登录...放行.....");
            return true;
        }

        //拿这个token对比存储到redis的token。
        //获取redis中的token
        String s = redisTemplate.opsForValue().get("TOKEN:" + token);
        if (StringUtils.isBlank(s)) {
            throw new  RuntimeException("令牌为空，未登录.....");
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
